<?php
/**
 * Created by PhpStorm.
 * User: zhanglihe
 * Date: 2018/6/4
 * Time: 上午10:30
 */

namespace Modules\Token\Driver;

class StorageRedis implements StorageInterface
{
    protected $redis;

    const HASH_KEY = '__TOKEN_HASH_KEY__';

    const CACHE_TTL_KEY = '__TOKEN_CACHE_TTL_KEY__';

    /**
     * 有效时间（分钟）
     *
     * @var
     */
    protected $minutes;

    protected $options;

    public function __construct($options)
    {
        $this->redis = app('redis');
    }

    public function has($key)
    {
        return $this->redis->hexists(self::HASH_KEY, $key);
    }

    public function put($key, Array $data)
    {
        $minutes = $this->minutes;
        $this->redis->pipeline(function ($pipe) use ($key, $data, $minutes) {
            $pipe->hset(self::HASH_KEY, $key, json_encode($data));
            $pipe->zadd(self::CACHE_TTL_KEY, time() + ($minutes * 60), $key);
        });
    }

    public function get($key)
    {
        $data = $this->redis->hget(self::HASH_KEY, $key);
        return json_decode($data, true);
    }

    public function forget($key)
    {
        $this->redis->hdel(self::HASH_KEY, $key);
    }

    public function all()
    {
        return $this->redis->hgetall(self::HASH_KEY);
    }

    public function flushExpired()
    {
        $expired = $this->redis->zrangebyscore(self::CACHE_TTL_KEY, 0, time());
        $this->redis->pipeline(function ($pipe) use ($expired) {
            $pipe->hdel($expired);
            $pipe->zrem($expired);
        });
    }
}